﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;

namespace WindowsFormsApplication1.WebTest.WebTestXmlNodes
{
    [XmlRoot("StringHttpBody", Namespace = XmlNamespace)]
    public class StringHttpBodyNode : GenericWebTestNode, IXmlSerializable
    {
        const int MaxStringBodyLength = 255;

        public override void SetNodeProperties()
        {
            SelectedImageIndex = 2;
            ImageIndex = 2;

            Text = "String Body";
        }

        #region IXmlSerializable Members

        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(XmlReader reader)
        {
            Notification.BeginOperation("Processing StringHttpBody Node", NodeOperationEventArgs.EventImportance.Detailed);

            //Read Validation Rule attributes
            ReadXmlAttributes(reader);

            //Set node properties such as Icon, Text, etc..
            SetNodeProperties();

            //Read the opening tag
            reader.MoveToContent();
            bool isEmptyElement = reader.IsEmptyElement;

            reader.Read();

            #region Read tag content

            byte[] buff = new byte[MaxStringBodyLength];
            int readBytes;

            MemoryStream stream = new MemoryStream();
            BinaryWriter binarywriter = new BinaryWriter(stream);

            while ((readBytes = reader.ReadContentAsBase64(buff, 0, buff.Length)) > 0)
                binarywriter.Write(buff, 0, readBytes);

            string stringBodyContent = Encoding.Unicode.GetString(stream.ToArray());
            
            NodeDescriptionProperties nodeParameters = new NodeDescriptionProperties(this)
                                                           {
                                                               Name = "Content",
                                                               Value = stringBodyContent,
                                                               WebTestNodeType = NodeDescriptionProperties.WebTestNodeTypes.Content
                                                           };

            _nodeProperties.Add(nodeParameters.Name, nodeParameters);

            #endregion

            //If there is closing tag read it
            if (!isEmptyElement)
                reader.ReadEndElement();

            Notification.EndOperation();
        }


        #endregion

    }
}
